<?php

namespace App\Http\Controllers\API\Tweet;

use Auth;
use Validator;
use App\Models\API\Tweet;
use Illuminate\Http\Request;
use App\Services\AliyunOSS\OSS;
use App\Http\Controllers\API\APIController;

class TweetController extends APIController
{
    public function index($userId)
    {
    	$tweets = Tweet::where('tweets.user_id', $userId)
            ->join('users', 'tweets.user_id', '=', 'users.id')
            // ->join('activities', 'activities.id', '=', 'tweets.source')
            // ->select('tweets.*', 'users.user_name', 'users.user_img', 'activities.title')
            ->select('tweets.*', 'users.user_name', 'users.user_img')
            ->paginate();
    	return response()->json($this->setJson(true, $tweets), 200);
    }

	public function tweet(Request $request)
	{
		$v = Validator::make($request->all(), [
			'user_id' => 'required',
            'source'  => 'required',
			// 'detail'  => 'required|max:255'
		]);

		if ($v->fails())
		{
			return response()->json($this->setJson(false, $v->errors()), 422);
		}

		if ($v->passes())
		{
			$userId = $request->get('user_id');
			$shareFile;

            $tweet = new Tweet;
            $tweet->user_id = $userId;
            $tweet->source = $request->get('source');

			if ($request->hasFile('share')) {
			    $shareFile = $request->file('share');
                $tweet->share = $this->upload($userId, $shareFile);
			}

			if (!empty($request->get('detail'))) {
                $tweet->detail = $request->get('detail');
            }

			$tweet->save();

			return response('tweet_succeed', 200);
		}
	}

    public function destroy(Request $request, $id)
    {
    	$userId = $request->get('user_id');

        $tweet = Tweet::where([
            ['id', '=', $id],
            ['user_id', '=', $userId]
        ])->first();

        OSS::deleteObject(substr($tweet->share, -25));
        
        $tweet->delete();
    	// $deleteTweet = Tweet::find($id)->delete();
    	return response()->json($this->setJson(true, 'delete_succeed'), 200);
    }

    private function setJson($status, $msg)
    {
        $res = [
            'status' => $status,
            'msg'    => $msg
        ];
        return $res;
    }

    /**
     * 上传图片
     *
     * @return string
     */
    private function upload($userId, $img)
    {
        // 文件名 userId + 秒 + 随机数 + .jpg
        $time = time();
        $rand = mt_rand(0000, 9999);
        $fileName = $userId.$time.$rand.'.'.$img->getClientOriginalExtension();

        $res = OSS::upload('share/'.$fileName, file_get_contents($img->getRealPath()));
        
        $pathName = 'http://imlooke.oss-cn-qingdao.aliyuncs.com/share/'.$fileName;
        // dd($img->getRealPath());
        return $pathName;
    }
}
